from analysis.models import KnowledgeMasteryProfile
from score.models import Subject


class AnalysisService:
    """分析计算服务"""

    def calculate_marginal_gain(self, student, knowledge_point):
        """
        计算边际收益：掌握这个知识点能提升多少分
        简化版：基于知识点权重和当前掌握度
        """
        try:
            profile = KnowledgeMasteryProfile.objects.get(
                student=student,
                knowledge_point=knowledge_point
            )
        except KnowledgeMasteryProfile.DoesNotExist:
            return 0.0

        # 边际收益 = (1 - 当前掌握度) × 知识点权重 × 满分比例
        improvement_potential = 1 - profile.mastery_level
        knowledge_weight = knowledge_point.weight or 1.0

        # 假设该知识点在考试中平均占5分
        base_score_impact = 5.0

        marginal_gain = improvement_potential * knowledge_weight * base_score_impact

        return round(marginal_gain, 1)

    def analyze_subject_status(self, student, subject):
        """分析科目整体状态"""
        profiles = KnowledgeMasteryProfile.objects.filter(
            student=student,
            knowledge_point__subject=subject
        )

        total_points = profiles.count()
        if total_points == 0:
            return {
                'average_mastery': 0,
                'weak_points_count': 0,
                'strong_points_count': 0,
                'estimated_score': 0
            }

        # 计算平均掌握度
        avg_mastery = sum(p.mastery_level for p in profiles) / total_points

        # 统计薄弱和优势知识点
        weak_points = profiles.filter(mastery_level__lt=0.6).count()
        strong_points = profiles.filter(mastery_level__gte=0.8).count()

        # 估算得分（基于掌握度和科目满分）
        subject_full_score = subject.full_score or 150
        estimated_score = avg_mastery * subject_full_score

        return {
            'average_mastery': round(avg_mastery, 3),
            'weak_points_count': weak_points,
            'strong_points_count': strong_points,
            'estimated_score': round(estimated_score, 1),
            'total_points': total_points
        }

    def get_learning_insights(self, student):
        """获取学习洞察"""
        profiles = KnowledgeMasteryProfile.objects.filter(
            student=student
        ).select_related('knowledge_point__subject')

        if not profiles.exists():
            return {"message": "暂无学习数据"}

        # 找出最需要改进的方面
        weakest_profile = profiles.order_by('mastery_level').first()
        strongest_profile = profiles.order_by('-mastery_level').first()

        # 分析趋势
        improving_count = profiles.filter(mastery_trend='improving').count()
        declining_count = profiles.filter(mastery_trend='declining').count()

        return {
            'weakest_knowledge_point': {
                'name': weakest_profile.knowledge_point.name,
                'mastery': round(weakest_profile.mastery_level, 3),
                'subject': weakest_profile.knowledge_point.subject.name
            },
            'strongest_knowledge_point': {
                'name': strongest_profile.knowledge_point.name,
                'mastery': round(strongest_profile.mastery_level, 3),
                'subject': strongest_profile.knowledge_point.subject.name
            },
            'trend_analysis': {
                'improving': improving_count,
                'declining': declining_count,
                'total': profiles.count()
            },
            'overall_progress': f"{(improving_count / profiles.count() * 100):.1f}%的知识点在提升中"
        }